package com.atguigu.eduorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.eduorder.entity.TOrder;
import com.atguigu.eduorder.entity.TPayLog;
import com.atguigu.eduorder.mapper.PayLogMapper;
import com.atguigu.eduorder.service.OrderService;
import com.atguigu.eduorder.service.PayLogService;
import com.atguigu.eduorder.utils.HttpClient;
import com.atguigu.servicebase.exception.MyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author shaki
 * @since 2021-06-25
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, TPayLog> implements PayLogService {

    @Resource
    private OrderService orderService;

    @Value("${weixin.pay.appid}")
    private String appid;
    @Value("${weixin.pay.partner}")
    private String partner;
    @Value("${weixin.pay.partnerkey}")
    private String partnerkey;
    @Value("${weixin.pay.notifyurl}")
    private String notifyurl;

    /**
     * 生成微信支付二维码接口
     * @param orderNo
     * @return
     */
    @Override
    public Map createNative(String orderNo) {
        try {
            //根据订单号查询订单信息
            QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            TOrder order = orderService.getOne(wrapper);
            //使用map设置二维码需要的参数
            Map<String,String> map = new HashMap<>();
            map.put("appid",appid);
            map.put("mch_id",partner);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body",order.getCourseTitle());
            map.put("out_trade_no",orderNo);
            map.put("total_fee",order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            map.put("spbill_create_ip","127.0.0.1");
            map.put("notify_url",notifyurl);
            map.put("trade_type","NATIVE");
            //发送HttpClient请求，传递参数转成xml格式
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(WXPayUtil.generateSignedXml(map,partnerkey));
            client.setHttps(true);
            client.post();
            //返回结果
            //contant是xml格式
            String content = client.getContent();
            Map<String,String> resultMap = WXPayUtil.xmlToMap(content);
            //最终返回数据的封装
            Map result = new HashMap();
            result.put("out_trade_no", orderNo);
            result.put("course_id", order.getCourseId());
            result.put("total_fee", order.getTotalFee());
            result.put("result_code", resultMap.get("result_code"));  //返回二维码操作状态码
            result.put("code_url", resultMap.get("code_url"));        //二维码地址

            return result;
        }catch (Exception e){
            throw new MyException(20001,"生成二维码失败！");
        }
    }

    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            //使用map设置二维码需要的参数
            Map<String,String> map = new HashMap<>();
            map.put("appid",appid);
            map.put("mch_id",partner);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("out_trade_no",orderNo);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(map,partnerkey));
            client.setHttps(true);
            client.post();
            //返回结果
            //contant是xml格式
            String content = client.getContent();
            Map<String,String> resultMap = WXPayUtil.xmlToMap(content);
            //最终返回数据的封装
            return resultMap;
        }catch (Exception e){
            throw new MyException(20001,"查询订单支付状态失败");
        }

    }

    /**
     * 添加支付记录和更新订单状态
     * @param map
     */
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //从map获取订单号
        String orderNo = map.get("out_trade_no");
        //根据订单号查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);

        //更新订单表订单状态
        if(order.getStatus().intValue() == 1) { return; }
        order.setStatus(1);//1代表已经支付
        orderService.updateById(order);

        //向支付表添加支付记录
        TPayLog payLog = new TPayLog();
        payLog.setOrderNo(orderNo);  //订单号
        payLog.setPayTime(new Date()); //订单完成时间
        payLog.setPayType(1);//支付类型 1微信
        payLog.setTotalFee(order.getTotalFee());//总金额(分)

        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id")); //流水号
        payLog.setAttr(JSONObject.toJSONString(map));

        baseMapper.insert(payLog);
    }
}
